package org.zheng.shop.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Objects;
import java.util.UUID;

@Service
public class FileStorageService {

    @Value("${file.upload-dir}")
    private String uploadDir;

    public String storeFile(MultipartFile file) {
        try {
            // 创建根目录和images子目录（如果不存在）
            Path uploadPath = Paths.get(uploadDir).toAbsolutePath().normalize();
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 创建images子目录
            Path imagesPath = uploadPath.resolve("images");
            if (!Files.exists(imagesPath)) {
                Files.createDirectories(imagesPath);
            }

            // 获取文件名
            String originalFilename = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
            
            // 生成唯一文件名避免覆盖
            String fileExtension = "";
            if (originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String filename = UUID.randomUUID() + fileExtension;

            // 复制文件到images目录
            Path targetLocation = imagesPath.resolve(filename);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            
            // 在日志中输出文件保存路径，方便调试
            System.out.println("文件已保存到: " + targetLocation.toString());

            return filename;
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new RuntimeException("无法存储文件。请重试!", ex);
        }
    }

    public void deleteFile(String filename) {
        try {
            // 尝试删除根目录下的文件
            Path filePath = Paths.get(uploadDir).toAbsolutePath().normalize().resolve(filename);
            boolean deleted = Files.deleteIfExists(filePath);
            
            if (!deleted) {
                // 如果根目录没有，尝试删除images子目录下的文件
                Path imagesPath = Paths.get(uploadDir).toAbsolutePath().normalize().resolve("images");
                Path imageFilePath = imagesPath.resolve(filename);
                Files.deleteIfExists(imageFilePath);
            }
        } catch (IOException ex) {
            throw new RuntimeException("无法删除文件。", ex);
        }
    }
} 